<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span style="font-size: 20px; font-weight: bold;">上传报告</span>
      </div>
    </template>
    <el-form :model="form" label-width="120px">
      <!-- 商户选择器 -->
      <el-form-item label="选择商户">
        <el-select style="width: 250px;" filterable v-model="selectedMerchantId" placeholder="请选择商户"
          :loading="loadingMerchants" @change="handleMerchantChange" popper-class="merchant-select-dropdown">
          <el-option v-for="item in merchantList" :key="item.id" :label="item.name" :value="item.id" />
          <el-option v-if="loadingMore" disabled key="loading-more">
            <div style="text-align: center; color: #999;">加载中...</div>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 上传相关功能已隐藏 -->
      <!--
      <el-form-item label="上传md文件">
        <el-upload :http-request="customUpload" :on-remove="handleRemove" :show-file-list="true" :limit="2"
          :on-exceed="handleExceed" accept=".md" multiple @change="handleChange">
          <el-button type="primary" :loading="uploading">上传md文件</el-button>
          <template #tip>
            <div class="el-upload__tip">请上传两个md文件，系统将自动合并内容</div>
          </template>
        </el-upload>
        <div v-if="uploading" class="upload-progress">
          <el-progress :percentage="uploadProgress" :format="format" />
          <span class="upload-text">正在解析文件...</span>
        </div>
      </el-form-item>
      <el-form-item label="上传到文件系统">
        <el-button type="success" @click="getMerchantFiles(selectedMerchant.id)">获取报告文件</el-button>
      </el-form-item>
      -->

      <!-- 显示解析后的内容 -->
      <el-form-item label="解析内容">
        <el-input v-model="form.content" :disabled="true" type="textarea" :rows="20" placeholder="解析后的内容将显示在这里" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :disabled="!form.content" @click="AIGenerateReportData">撰写分析报告</el-button>
      </el-form-item>
      <el-form-item label="流量分析报告">
        <slot name="reportContent"></slot>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 全屏遮罩和进度条 -->
  <div v-if="percentage > 0" class="overlay">
    <div class="progress-wrapper">
      <div class="progress-content">
        <div class="progress-title">
          <span class="ai-icon">🤖</span>
          AI正在分析数据
        </div>
        <el-progress :percentage="Math.min(smoothPercentage, 100)" :stroke-width="8" :show-text="false"
          class="custom-progress" />
        <div class="progress-status">
          <span class="percentage-text">{{ formatPercentage(Math.min(smoothPercentage, 100)) }}%</span>
          <span class="status-text">{{ getProgressStatus() }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick, watch, onUnmounted, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getDecision, getMerchantList, getMerchantData, type Merchant } from '../api'

// 定义商户类型
interface MerchantType {
  id: string;
  name: string;
}

// 定义商户列表响应类型
interface MerchantListResponse {
  code: number;
  data: {
    list: Merchant[];
    total: number;
  };
  message?: string;
}

const selectedMerchantId = ref('')
const form = ref({
  title: '',
  content: '',
  AIContent: ''
})

// 商户选择
const selectedMerchant = ref<MerchantType>({ id: '', name: '' })
const merchantList = ref<Array<MerchantType>>([])
const loadingMerchants = ref(false)
const loadingMore = ref(false)

const emit = defineEmits(['exportReportData', 'exportAiContent'])
const percentage = ref(0)

// 添加分页相关的状态变量
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 使用ElMessage
const Message = ElMessage

// 进度条控制相关
const smoothPercentage = ref(0)
let progressInterval: number | null = null
let smoothInterval: number | null = null
let isApiReturned = false
const TARGET_DURATION = 75000 // 目标总时长：75秒
const TARGET_PERCENTAGE = 90 // 目标进度：90%
let startTime: number | null = null

// 获取商户列表
const fetchMerchantList = async (isLoadMore = false) => {
  if (isLoadMore) {
    loadingMore.value = true
  } else {
    loadingMerchants.value = true
  }
  try {
    const response = await getMerchantList({
      page_num: pageNum.value,
      page_size: pageSize.value
    }) as MerchantListResponse
    
    if (response && response.code === 200 && response.data) {
      const newList = response.data.list.map((item: Merchant) => ({
        id: item.code,
        name: item.name
      }))
      if (isLoadMore) {
        merchantList.value = [...merchantList.value, ...newList]
      } else {
        merchantList.value = newList
        Message.success('获取商户列表成功')
      }
      total.value = response.data.total || 0
    } else {
      throw new Error(response?.message || '获取商户列表失败')
    }
  } catch (error: any) {
    console.error('获取商户列表失败:', error)
    Message.error(`获取商户列表失败: ${error instanceof Error ? error.message : '未知错误'}`)
  } finally {
    if (isLoadMore) {
      loadingMore.value = false
    } else {
      loadingMerchants.value = false
    }
  }
}

// 滚动加载更多商户
const loadMoreMerchants = () => {
  if (merchantList.value.length < total.value && !loadingMore.value) {
    pageNum.value++
    fetchMerchantList(true)
  }
}

// 修改handleMerchantChange函数
const handleMerchantChange = async (value: string) => {
  console.log('选择的商户ID:', value)
  ElMessage.warning(value)
  if (!value) {
    ElMessage.warning('请选择商户')
    return
  }

  // 重置上传状态
  const selectedMerchantName = merchantList.value.find(item => item.id === value)?.name
  if (!selectedMerchantName) {
    ElMessage.error('未找到商户信息')
    return
  }

  selectedMerchant.value = {
    id: value,
    name: selectedMerchantName
  }
  form.value.content = ''
  
  try {
    // 从后端服务获取数据
    const response = await getMerchantData(value)
    
    if (response && response.code === 200 && response.data) {
      const data = response.data

      // 构建要传递的数据对象
      const exportData = {
        matchedData: data,
        selectedMerchant: {
          value: {
            id: selectedMerchant.value.id,
            name: selectedMerchant.value.name
          }
        }
      }
      
      emit('exportReportData', exportData)
      
      // 将数据格式化为文本显示
      form.value.content = data.map(section => {
        if (!section || !section.title || !Array.isArray(section.items)) {
          return ''
        }
        return `${section.title}:\n${section.items.map(item => {
          if (!item || !item.name) {
            return ''
          }
          if (Array.isArray(item.value)) {
            return `  ${item.name}: [${item.value.length}条数据]`
          }
          return `  ${item.name}: ${item.value || ''}`
        }).filter(Boolean).join('\n')}`
      }).filter(Boolean).join('\n\n')
      
      ElMessage.success('获取商户数据成功')
    } else {
      throw new Error(response?.message || '获取数据失败')
    }
  } catch (error: any) {
    console.error('获取商户数据失败:', error)
    ElMessage.error(`获取商户数据失败: ${error instanceof Error ? error.message : '未知错误'}`)
  }
}

// 修改进度状态文本函数
const getProgressStatus = () => {
  const currentPercentage = Math.min(percentage.value, 100)
  if (currentPercentage < 5) return '正在初始化分析环境...'
  if (currentPercentage < 10) return '正在连接数据源，请稍候...'
  if (currentPercentage < 15) return '数据连接成功，开始读取数据...'
  if (currentPercentage < 20) return '正在读取历史数据记录...'
  if (currentPercentage < 25) return '数据读取完成，开始数据预处理...'
  if (currentPercentage < 30) return '正在清洗和标准化数据...'
  if (currentPercentage < 35) return '数据预处理完成，开始特征提取...'
  if (currentPercentage < 40) return '正在分析数据特征和模式...'
  if (currentPercentage < 45) return '发现了一些有趣的数据趋势...'
  if (currentPercentage < 50) return '正在深入分析业务数据...'
  if (currentPercentage < 55) return 'AI正在思考数据背后的含义...'
  if (currentPercentage < 60) return '正在识别关键业务指标...'
  if (currentPercentage < 65) return '正在分析数据之间的关联性...'
  if (currentPercentage < 70) return '正在生成初步分析结论...'
  if (currentPercentage < 75) return '正在组织分析报告结构...'
  if (currentPercentage < 80) return '正在撰写分析报告内容...'
  if (currentPercentage < 85) return '正在优化报告表述...'
  if (currentPercentage < 90) return '正在添加数据可视化建议...'
  if (currentPercentage < 95) return '正在做最后的报告优化...'
  if (currentPercentage < 100) return '报告即将完成，正在做最后的润色...'
  return '报告生成完成！✨'
}

// 生成随机延迟时间
const getRandomDelay = () => {
  return Math.floor(Math.random() * 400) + 100 // 0.1-0.5秒之间
}

// 计算当前应该达到的进度
const calculateTargetProgress = () => {
  if (!startTime) return 0
  const elapsed = Date.now() - startTime
  const progress = Math.min(elapsed / TARGET_DURATION, 1)
  return progress * TARGET_PERCENTAGE
}

// 生成随机进度增量
const getRandomIncrement = () => {
  const targetProgress = calculateTargetProgress()
  const currentProgress = percentage.value
  
  if (targetProgress - currentProgress <= 0) return 0
  
  const baseIncrement = (Math.random() * 0.3) + 0.1 // 0.1-0.4之间
  
  // 如果进度落后，增加增量
  if (currentProgress < targetProgress * 0.8) {
    return baseIncrement * 1.5
  }
  // 如果进度超前，减少增量
  if (currentProgress > targetProgress * 1.2) {
    return baseIncrement * 0.5
  }
  
  return baseIncrement
}

// 启动进度条更新
const startProgressUpdate = () => {
  // 重置进度
  percentage.value = 0
  smoothPercentage.value = 0
  isApiReturned = false
  startTime = Date.now()
  
  // 创建进度更新定时器
  progressInterval = setInterval(() => {
    if (!isApiReturned && percentage.value < TARGET_PERCENTAGE) {
      const increment = getRandomIncrement()
      if (increment > 0) {
        percentage.value += increment
      }
    }
  }, getRandomDelay())
  
  // 创建平滑过渡定时器
  smoothInterval = setInterval(() => {
    if (smoothPercentage.value < percentage.value) {
      smoothPercentage.value += 0.1
    }
  }, 20)
}

// 停止进度条更新
const stopProgressUpdate = () => {
  if (progressInterval) {
    clearInterval(progressInterval)
    progressInterval = null
  }
  if (smoothInterval) {
    clearInterval(smoothInterval)
    smoothInterval = null
  }
}

// 设置最终进度
const setFinalProgress = async () => {
  isApiReturned = true
  
  // 如果当前进度小于90，先平滑过渡到95
  if (percentage.value < 90) {
    const targetPercentage = 95
    const duration = 1500 // 1.5秒
    const startTime = Date.now()
    const startPercentage = percentage.value
    
    while (percentage.value < targetPercentage) {
      const elapsed = Date.now() - startTime
      const progress = Math.min(elapsed / duration, 1)
      percentage.value = startPercentage + (targetPercentage - startPercentage) * progress
      await new Promise(resolve => setTimeout(resolve, 20))
    }
  }
  
  // 然后平滑过渡到100
  const duration = 1000 // 1秒
  const startTime = Date.now()
  const startPercentage = percentage.value
  
  while (percentage.value < 100) {
    const elapsed = Date.now() - startTime
    const progress = Math.min(elapsed / duration, 1)
    percentage.value = startPercentage + (100 - startPercentage) * progress
    await new Promise(resolve => setTimeout(resolve, 20))
  }
  
  // 等待平滑过渡完成
  setTimeout(() => {
    percentage.value = 0
    smoothPercentage.value = 0
  }, 500)
}

// 格式化百分比显示
const formatPercentage = (value: number) => {
  return value.toFixed(1)
}

const AIGenerateReportData = async () => {
  // 启动进度条更新
  startProgressUpdate()
  
  try {
    // 使用form.value.content作为分析内容
    const res = await getDecision({
      report_data: form.value.content
    })
    console.log("🚀 ~ getDecision ~ res:", res)
    
    // 确保访问正确的属性路径并使用类型断言
    const analysis = (res as any)?.analysis?.markdown
    if (!analysis) {
      throw new Error('分析结果格式不正确')
    }
    
    emit('exportAiContent', analysis)
    form.value.AIContent = analysis
    
    // 设置最终进度
    await setFinalProgress()
    Message.success('报告生成成功')

    // 添加滚动到新生成内容的位置
    nextTick(() => {
      const aiContentElement = document.querySelector('.ai-content')
      if (aiContentElement) {
        aiContentElement.scrollIntoView({
          behavior: 'smooth',
          block: 'start'
        })
      }
    })
  } catch (error: any) {
    // 停止进度条更新
    stopProgressUpdate()
    console.error('生成报告失败:', error)
    Message.error('生成报告失败，请重试')
    percentage.value = 0
    smoothPercentage.value = 0
  }
}

// 监听 percentage 变化来控制 body 样式
watch(() => percentage.value, (newVal) => {
  if (newVal > 0) {
    document.body.classList.add('overlay-visible')
  } else {
    document.body.classList.remove('overlay-visible')
  }
})

// 组件卸载时清理
onUnmounted(() => {
  stopProgressUpdate()
  document.body.classList.remove('overlay-visible')
})

// 初始化时获取商户列表
onMounted(() => {
  fetchMerchantList()

  // 使用事件委托来处理滚动事件，因为下拉列表是动态创建的
  // 并使用 nextTick 确保在 DOM 更新后执行
  nextTick(() => {
    const selectDropdown = document.querySelector('.merchant-select-dropdown .el-select-dropdown__wrap')
    if (selectDropdown) {
      selectDropdown.addEventListener('scroll', (event) => {
        const el = event.target as HTMLElement
        if (el.scrollHeight - el.scrollTop - el.clientHeight < 10 && !loadingMore.value) {
          loadMoreMerchants()
        }
      })
    }
  })
})

// 添加默认导出
defineOptions({
  name: 'ReportUpload'
})
</script>

<style scoped>
.box-card {
  position: relative;
  width: 50%;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  margin: 0;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #e2e8f0;
}

:deep(.el-card__body) {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
}

:deep(.el-form) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-form-item) {
  margin-bottom: 15px;
}

/* :deep(.el-form-item:last-child) {
  flex: 1;
  margin-bottom: 0;
  display: flex;
  flex-direction: column;
} */

:deep(.el-form-item__content) {
  flex: 1;
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  color: #1a365d;
  font-size: 16px;
  font-weight: 600;
}

:deep(.el-form-item__label) {
  color: #4a5568;
  font-weight: 500;
}

.upload-progress {
  margin-top: 10px;
  width: 100%;
}

.upload-text {
  display: block;
  margin-top: 5px;
  font-size: 12px;
  color: #64748b;
  text-align: center;
}

:deep(.el-upload__tip) {
  font-size: 12px;
  color: #64748b;
  margin-top: 5px;
}

/* 进度条遮罩层 */
.overlay {
  position: fixed;
  inset: 0;
  /* 替代 top/right/bottom/left */
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(2px);
  min-width: 100vw;
  min-height: 100vh;
  overflow: hidden;
  padding: 0;
  margin: 0;
}

.progress-wrapper {
  width: 400px;
  padding: 30px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  position: relative;
  z-index: 10000;
}

.progress-title {
  font-size: 18px;
  font-weight: 600;
  color: #1a365d;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.ai-icon {
  font-size: 20px;
}

.custom-progress {
  margin-bottom: 20px;
}

:deep(.el-progress-bar__outer) {
  background-color: #e2e8f0 !important;
  border-radius: 4px;
}

:deep(.el-progress-bar__inner) {
  background: linear-gradient(90deg, #3b82f6, #60a5fa);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-status {
  margin-top: 15px;
  text-align: center;
}

.percentage-text {
  font-size: 24px;
  font-weight: bold;
  color: #1a365d;
}

.status-text {
  font-size: 14px;
  color: #64748b;
  margin-top: 5px;
}

/* 动画效果 */
.overlay {
  animation: fadeIn 0.2s ease;
}

.progress-wrapper {
  animation: slideUp 0.2s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    transform: translateY(10px);
    opacity: 0;
  }

  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* 添加一个额外的样式来防止页面滚动 */
:deep(body.overlay-visible) {
  overflow: hidden;
}
</style>